import base from '../api/base'

const module = 'users'

const state = {
  list: [],
  editNode: null,
  page: {
    number: 0,
    size: 5,
    totalElements: 0,
    totalPages: 0
  }
}

const getters = {}

const actions = {
  reLoad ({ dispatch, state }) {
    dispatch('getList', {
      page: state.page.number
    })
  },
  getList ({ commit }, params = {}) {
    base.find({
      cb: result => {
        commit('setList', {
          list: result._embedded[module],
          page: result.page.number
        })
        commit('setPage', result.page)
      },
      ecb: error => {
        if (error && error.response && error.response.status === 304) {
          commit('setPageNum', params.page || 0)
        }
      },
      module,
      params: {
        projection: 'UserWithSimple',
        sort: 'num',
        ...params
      }
    })
  },
  remove ({ dispatch }, params) {
    const { ecb, ...others } = params
    base.remove({
      ...others,
      ecb: error => {
        ecb && ecb(error)
        // 通过单独获取一个节点并添加到结尾避免全部刷新
        dispatch('reLoad')
      }
    })
  },
  delete ({ dispatch }, selection) {
    let idList = []
    for (let i in selection) {
      idList.push(selection[i].id)
    }
    base.delete({
      cb: result => {
        console.log(result)
        dispatch('reLoad')
      },
      ecb: error => {
        console.log(error)
      },
      module,
      idList
    })
  },
  create ({ state }, params) {
    base.create({ module, ...params })
  },
  update ({ commit, dispatch, state }, params) {
    const { formData, cb, ...others } = params
    base.update({
      formData,
      cb: result => {
        if (formData.num === state.editNode.num) {
          const newList = state.list
          for (let i in newList) {
            if (newList[i].id === state.editNode.id) {
              newList[i].name = formData.name
              newList[i].description = formData.description
              break
            }
          }
          commit('setList', newList)
        } else {
          dispatch('reLoad')
        }
        cb && cb(result)
      },
      ...others
    })
  },
  setEditNode ({ commit, state }, index) {
    commit('setEditNode', state.list[state.page.number][index])
  }
}

// mutations
const mutations = {
  setList (state, { list, page }) {
    state.list[page] = list
  },
  setPage (state, page) {
    state.page = page
  },
  setPageNum (state, num) {
    state.page.number = num
  },
  setEditNode (state, editNode) {
    state.editNode = editNode
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
